package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"
	"wego/utils"
)

type Admin struct {
	Id         int64  `json:"id"`
	Username   string `json:"username"`
	Password   string `json:"password"`
	Nickname   string `json:"nickname"`
	Email      string `json:"email"`
	Mobile     string `json:"mobile"`
	Status     int8   `json:"status"`
	Remark     string `json:"remark"`
	CreateTime int64  `json:"create_time"`
	UpdateTime int64  `json:"update_time"`
	//GroupId    []int  `json:"group_id" orm:"-" form:"GroupId"`
	GroupId string `json:"group_id" orm:"-" form:"GroupId"`
}

func AdminList(params *BaseQueryParam) ([]*Admin, int64) {
	sortorder := "-Id"
	query := orm.NewOrm().QueryTable("tp_admin")
	data := make([]*Admin, 0)
	total, _ := query.Count()
	_, _ = query.OrderBy(sortorder).Limit(params.Size, (params.Page-1)*int64(params.Size)).All(&data)
	for _, item := range data {
		//item.GroupId = utils.String2Array(GetGroupId(item.Id))
		item.GroupId = GetGroupId(item.Id)
	}
	return data, total
}

type GetAdminParams struct {
	BaseQueryParam
	GroupId int64 `json:"gid"`
}

//获取当前用户组成员
func GetAdminByGroupId(params *GetAdminParams) ([]Admin, int64) {
	o := orm.NewOrm()
	lists := []*AuthGroupAccess{}
	cond := orm.NewCondition()
	conds := cond.Or(
		"group_id__contains", ","+strconv.Itoa(int(params.GroupId))+",").Or(
		"group_id__startswith", "["+strconv.Itoa(int(params.GroupId))+",").Or(
		"group_id__endswith", ","+strconv.Itoa(int(params.GroupId))+"]").Or(
		"group_id__exact", "["+strconv.Itoa(int(params.GroupId))+"]")
	_, _ = o.QueryTable("tp_auth_group_access").SetCond(conds).All(&lists)

	arr := []int64{}
	for _, item := range lists {
		arr = append(arr, item.Uid)
	}
	list := []Admin{}
	sortorder := "Id"
	qs := o.QueryTable("tp_admin")
	_, _ = qs.Filter("id__in", arr).OrderBy(sortorder).Limit(params.Size, (params.Page-1)*int64(params.Size)).All(&list)
	num, _ := qs.Filter("id__in", arr).Count()
	return list, num
}

func AdminSave(m *Admin) error {
	o := orm.NewOrm()
	err := o.Begin()

	if m.Id != 0 {
		if m.Password != "YCMS" {
			m.Password = utils.Md5(utils.Sha1(m.Password) + beego.AppConfig.String("authkey"))
			_, err = o.Update(m, "username", "password", "nickname")
		} else {
			_, err = o.Update(m, "username", "nickname")
		}

	} else {
		m.Password = utils.Md5(utils.Sha1(m.Password) + beego.AppConfig.String("authkey"))
		ctime := time.Now().Unix()
		m.Status = 1
		m.CreateTime = ctime
		m.UpdateTime = ctime
		m.Id, err = o.Insert(m)
	}

	if err != nil {
		err = o.Rollback()
	} else {
		r := AuthGroupAccess{Uid: m.Id}
		er := o.Read(&r, "Uid")
		r.GroupId = m.GroupId

		if er == nil {
			_, err = o.Update(&r)
		} else {
			_, err = o.Insert(&r)
		}
		if err != nil {
			err = o.Rollback()
		} else {
			err = o.Commit()
		}
	}
	return err
}

func AdminStatus(m *Admin) error {
	o := orm.NewOrm()
	_, err := o.Update(m, "status")
	return err
}

func GetAdmin(username, password string) (*Admin, error) {
	m := &Admin{}
	err := orm.NewOrm().QueryTable("tp_admin").Filter("username", username).Filter("password", password).One(m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func AdminDel(m *Admin) error {
	o := orm.NewOrm()
	err := o.Begin()
	_, err = o.QueryTable("tp_admin").Filter("id", m.Id).Delete()
	if err == nil {
		_, err = o.QueryTable("tp_auth_group_access").Filter("uid", m.Id).Delete()
	}
	if err != nil {
		err = o.Rollback()
	} else {
		err = o.Commit()
	}
	return err
}
